package icu.lookyousmileface.threadpool;

import com.sun.org.apache.bcel.internal.generic.NEW;

import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author starrysky
 * @title: ThreadPoolExecutorUse
 * @projectName Juc_Pro
 * @description: 准守阿里巴巴线程池创建规范
 * Executors工具类3方法
 * 4种策略
 * 银行总的人数：max+queue
 * new ThreadPoolExecutor.AbortPolicy()银行满了，再来人就会跑出异常
 * new ThreadPoolExecutor.CallerRunsPolicy()银行满了，让主线程执行
 * new ThreadPoolExecutor.DiscardPolicy()队列满了，丢掉任务，不报错
 * new ThreadPoolExecutor.DiscardOldestPolicy()银行满了，让进来的人和最开进银行的人进行线程竞争
 * @date 2021/1/2910:42 下午
 */
public class ThreadPoolExecutorUse {
    public static void main(String[] args) {
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                /**
                 * 七大参数
                 */
                2, //正常营业的两个窗口
                Runtime.getRuntime().availableProcessors(),//银行最大的窗口数
                2,//当备用的3个窗口闲置时间超过此值，就会关闭线程（窗口）
                TimeUnit.SECONDS,//闲置时间的单位
                new LinkedBlockingQueue<>(3),//等待区等待数量阻塞队列，注意4组api
                Executors.defaultThreadFactory(),//线程工程，默认不动
                new ThreadPoolExecutor.DiscardPolicy()
        );

        try {
            for (int i = 1; i <= 10; i++) {
                threadPoolExecutor.execute(()->{
                    System.out.println(Thread.currentThread().getName()+"=>ok");
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            threadPoolExecutor.shutdown();
        }
    }
}
